/*
 * @Author: your name
 * @Date: 2020-06-29 14:56:45
 * @LastEditTime: 2020-07-06 16:10:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \thinkjs-test\src\service\PushService.js
 */
var GeTui = require('gt-push-sdk');
var Target = require('gt-push-sdk/getui/Target');
var BaseTemplate = require('gt-push-sdk/getui/template/BaseTemplate');
var TransmissionTemplate = require('gt-push-sdk/getui/template/TransmissionTemplate');
var AppMessage = require('gt-push-sdk/getui/message/AppMessage');
var ListMessage = require('gt-push-sdk/getui/message/ListMessage');
var SingleMessage = require('gt-push-sdk/getui/message/SingleMessage');
var Notify = require('gt-push-sdk/getui/template/notify/Notify');
module.exports = class extends think.Service {
    constructor() {
        super();


        this.CID = "390179eae678a4ea3b7dbcdda28b8529"; //测试用cid
        this.CID2 = "eb515862481b112a966f161b262953ea"; //测试用cid
        this.CID3 = "bb9e0c013d18d9c3b459bdf8b1aa34b5";
        this.CID4 = "9ef8b637e360aa35bcc28365cfa5a251";//殷童手机
        this.GTConfig = think.config("geTuiConfig");
        this.GTClinet = new GeTui(this.GTConfig.HOST, this.GTConfig.APPKEY, this.GTConfig.MASTERSECRET);
    }


    /**
     *单推
     *
     * @param {*} data{
     * CID:客户端唯一标识
     * }
     * @returns
     */
    pushMessageToSingle(data) {

        const CID = data && data.CID || this.CID3;
        const alias = data && data.alias ||'';
        const title = data && data.title || "小米测试消息title123";
        const content = data && data.content || "小米测试消息content123";
        let payload = data && data.payload || {title:"test",content:"test payload content"};
        if(payload && typeof payload == 'object'){
            payload = JSON.stringify(payload);
        }

        // 生成指定格式的intent支持厂商推送通道
        const intent = `$intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=${this.GTConfig.package}/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=${title};S.content=${content};S.payload=${payload};end";`;

        console.log('intent:',intent);
        // 定义"点击链接打开通知模板"，并设置透传内容，透传形式
        const message = this.createSingleMessage(title, content, intent, payload);
        const gtClinet = this.GTClinet;

        //接收方
        if(alias){
            var target = new Target({
                appId: this.GTConfig.APPID,
                alias:alias
            });
        }else if(CID){
            var target = new Target({
                appId: this.GTConfig.APPID,
                clientId: CID
            });
        }
        
        

        return new Promise(function (resolve, reject) {
            gtClinet.pushMessageToSingle(message, target, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }

            });
        })
    }


/**
     *创建消息体
     *
     * @param {*} title 标题
     * @param {*} conent 内容
     * @param {*} intent 离线推送结构体
     * @param {*} payload 其他信息
     * @returns
     */
    createSingleMessage(title, conent, intent, payload) {

        var template = new TransmissionTemplate({
            appId: this.GTConfig.APPID,
            appKey: this.GTConfig.APPKEY,
            transmissionType: 1,
            transmissionContent: payload
        });
        //兼容使用厂商通道传输
        var notify = new Notify({
            title: title, //'透传测试内容1111_title',
            content: conent, //'透传测试内容1111_content',
            intent: intent,
            payload:payload,
            "click_type":"startapp",
            type:1,
        });
        template.set3rdNotifyInfo(notify);


        //定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
        var message = new SingleMessage({
            isOffline: false,
            offlineExpireTime: 3600 * 12 * 1000,
            data: template,
        });
        return message;
    }

    /**
     *创建app消息体
     *
     * @param {*} title 标题
     * @param {*} conent 内容
     * @param {*} intent 离线推送结构体
     * @param {*} payload 其他信息
     * @returns
     */
    createAppMessage(title, conent, intent, payload,tagList) {

        var template = new TransmissionTemplate({
            appId: this.GTConfig.APPID,
            appKey: this.GTConfig.APPKEY,
            transmissionType: 1,
            transmissionContent: payload
        });
        //兼容使用厂商通道传输
        var notify = new Notify({
            title: title, //'透传测试内容1111_title',
            content: conent, //'透传测试内容1111_content',
            intent: intent,
            type: '1',
        });
        template.set3rdNotifyInfo(notify);


        //定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
        var message = new AppMessage({
            isOffline: false,
            offlineExpireTime: 3600 * 12 * 1000,
            data: template,
            appIdList: [this.GTConfig.APPID],
            //        phoneTypeList: ['IOS'],
            //        provinceList: ['浙江'],
            tagList: tagList||[],
            speed: 100
        });
        return message;
    }

    /**
     *创建消息体
     *
     * @param {*} title 标题
     * @param {*} conent 内容
     * @param {*} intent 离线推送结构体
     * @param {*} payload 其他信息
     * @returns
     */
    createListMessage(title, conent, intent, payload) {
        if(!intent){
            intent = `$intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=${this.GTConfig.package}/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=${title};S.content=${content};S.payload=${payload};end";`;
        }
        var template = new TransmissionTemplate({
            appId: this.GTConfig.APPID,
            appKey: this.GTConfig.APPKEY,
            transmissionType: 1,
            transmissionContent: payload
        });
        //兼容使用厂商通道传输
        var notify = new Notify({
            title: title, //'透传测试内容1111_title',
            content: conent, //'透传测试内容1111_content',
            intent: intent,
            type: '1',
        });
        template.set3rdNotifyInfo(notify);


        //定义"AppMessage"类型消息对象，设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
        var message = new ListMessage({
            isOffline: false,
            offlineExpireTime: 3600 * 12 * 1000,
            data: template,
            // appIdList: [this.GTConfig.APPID],
            //        phoneTypeList: ['IOS'],
            //        provinceList: ['浙江'],
            //tagList: ['阿百川']
            // speed: 10000
        });
        return message;
    }
    /**
     *对指定应用群推消息
     *data
     * @returns
     */
    pushMessageToApp(data) {
        const title = data && data.title || "小米群推测试消息title";
        const content = data && data.content || "小米群推测试消息content";
        const payload = data && data.payload || "test2";
        const taskGroupName = data && data.taskGroupName || '';//"taskGroupTest";
        const tagList = data&& data.tag?[data.tag]:[];

        // 生成指定格式的intent支持厂商推送通道
        const intent = `$intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=${this.GTConfig.package}/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=${title};S.content=${content};S.payload=${payload};end";`;

        // 定义"点击链接打开通知模板"，并设置透传内容，透传形式
        const message = this.createAppMessage(title, content, intent, payload,tagList);
        const gtClinet = this.GTClinet;


        return new Promise(function (resolve, reject) {
            if (taskGroupName) {
                gtClinet.pushMessageToApp(message, taskGroupName, function (err, res) {
                    if (err) {
                        reject(err)
                    } else if (res) {
                        resolve(res);
                    }
                });
            } else {
                gtClinet.pushMessageToApp(message, function (err, res) {
                    if (err) {
                        reject(err)
                    } else if (res) {
                        resolve(res);
                    }
                });
            }
        })
    }


    /**
     *绑定别名 单用户
     *
     * @param {*} data
     */
    bindAlias(data) {
        const alias = data && data.alias || 'demo';
        const APPID = this.GTConfig.APPID;
        const CID = data && data.cid || this.CID;
        const gtClinet = this.GTClinet;
        return new Promise(function (resolve, reject) {
            gtClinet.bindAlias(APPID, alias, CID, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }

            });
        })
    }

    /**
     *多个clientid绑定别名
     *
     * @param {*} data
     */
    bindAliasList(data) {
        const alias = data && data.alias || 'demo';
        const APPID = this.GTConfig.APPID;
        let CIDList = data && data.cidList || [this.CID];
        if (CIDList && typeof CIDList == 'string' && CIDList.indexOf(',') >= 0) {
            CIDList = CIDList.split(',');
        }
        const gtClinet = this.GTClinet;
        const targetList = CIDList.map(item => new Target({
            alias: alias,
            clientId: item
        }));

        return new Promise(function (resolve, reject) {
            gtClinet.bindAlias(APPID, targetList, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }

            });
        })
    }


    /**
     *根据别名获取clientid信息
     *
     * @param {*} data
     */
    queryClientId(data) {
        const alias = data && data.alias || 'demo';
        const APPID = this.GTConfig.APPID;
        const gtClinet = this.GTClinet;
        return new Promise(function (resolve, reject) {
            gtClinet.queryClientId(APPID, alias, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }

            });
        })
    }


    /**
     *通过clientid获取别名信息
     *
     * @param {*} data
     */
    queryAlias(data) {
        const CID = data && data.cid || this.CID;
        const APPID = this.GTConfig.APPID;
        const gtClinet = this.GTClinet;

        return new Promise(function (resolve, reject) {
            gtClinet.queryAlias(APPID, CID, function (err, res) {
                if (err) {
                    reject(err)
                }
                if (res) {
                    resolve(res);
                }

            });
        })
    }

    /**
     *单个clientid和别名解绑
     *
     * @param {*} data
     */
    unBindAlias(data) {
        const CID = data && data.cid || this.CID;
        const alias = data && data.alias || 'demo';
        const APPID = this.GTConfig.APPID;
        const gtClinet = this.GTClinet;

        return new Promise(function (resolve, reject) {
            //全部用户与别名解绑
            if (CID) {
                gtClinet.unBindAlias(APPID, alias, CID, function (err, res) {
                    if (err) {
                        reject(err)
                    }
                    if (res) {
                        resolve(res);
                    }

                });
            } else {
                //全部用户与别名解绑
                gtClinet.unBindAlias(APPID, alias, function (err, res) {
                    if (err) {
                        reject(err)
                    }
                    if (res) {
                        resolve(res);
                    }

                });
            }
        })
    }

    pushMessageToList(data) {
        const title = data && data.title || "群推测试消息title";
        const content = data && data.content || "群推测试消息content";
        const payload = data && data.payload || "test";

        // 生成指定格式的intent支持厂商推送通道
        const intent = `$intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=${this.GTConfig.package}/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=${title};S.content=${content};S.payload=${payload};end";`;

        // 定义"点击链接打开通知模板"，并设置透传内容，透传形式
        const message = this.createListMessage(title, content, intent, payload);
        const gtClinet = this.GTClinet;


        return new Promise(function (resolve, reject) {
            gtClinet.pushMessageToList(message, targets, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }
            });
        })
    }

    /**
     *根据taskGroupName获取taskid
     *
     * @param {*} data
     */
    getContentId(message, taskGroupName) {
        const gtClinet = this.GTClinet;
        return new Promise(function (resolve, reject) {
            gtClinet.getContentId(message, taskGroupName, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }
            });
        })
    }

    /**
     *对指定用户列表推送消息
     *
     * @param {*} data
     */
    async pushMessageToList(data) {
        const APPID = this.GTConfig.APPID;
        let CIDList = data && data.cidList || [this.CID, this.CID2];
        if (CIDList && typeof CIDList == "string" && CIDList.indexOf(',') >= 0) {
            CIDList = CIDList.split(',');
        }
        const alias = data && data.alias || '';
        const title = data && data.title || "tolist测试消息title";
        const content = data && data.content || "tolist测试消息content";
        const payload = data && data.payload || "tolisttest";
        const taskGroupName = data && data.taskGroupName || "taskGroupTest" + +new Date();

        // 生成指定格式的intent支持厂商推送通道
        const intent = `$intent = "intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=${this.GTConfig.package}/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=${title};S.content=${content};S.payload=${payload};end";`;

        // 定义"点击链接打开通知模板"，并设置透传内容，透传形式
        const message = this.createListMessage(title, content, intent, payload);
        const gtClinet = this.GTClinet;
        const contentId = await this.getContentId(message, taskGroupName);
        console.log('contentId:', contentId);
        const targetList = CIDList.map(item => new Target({
            appId: APPID,
            alias: alias,
            clientId: item
        }));

        return new Promise(function (resolve, reject) {
            gtClinet.pushMessageToList(contentId, targetList, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }
            });
        })
    }

    /**
     *对指定用户设置tag属性
     *
     * @param {*} data
     */
    setClientTag(data){
        const gtClinet = this.GTClinet;
        const APPID = this.GTConfig.APPID;
        const CID = data && data.cid || this.CID2;
        const tag = data && data.tag||'';
        let tagList = data && data.tagList || [];
        if(tag){
            tagList=[tag];
        }
        if(!tagList){
            return new Throw('tag is null');
        }else if(tagList && typeof tagList =='string' && tagList.indexOf(',')){
            tagList = tagList.split(',');
        } 
        console.log('tagList:',tagList);
        return new Promise(function (resolve, reject) {
            gtClinet.setClientTag(APPID, CID, tagList, function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }
            });
        })
    }


    /**
     *获取指定用户的tag属性
     *
     * @param {*} data
     */
    getUserTags(data){
        const gtClinet = this.GTClinet;
        const APPID = this.GTConfig.APPID;
        const CID = data && data.cid || this.CID;
        if(!CID){
            return new Throw('cid is null');
        }
        return new Promise(function (resolve, reject) {
            gtClinet.getUserTags(APPID, CID,  function (err, res) {
                if (err) {
                    reject(err)
                } else if (res) {
                    resolve(res);
                }
            });
        })
    }

}